package org.apogee.mil.server.database.helper;

import java.util.HashMap;

public class DatabaseConnector {
	
	public static final String ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver";
	public static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
	
	private String serverAddress = "localhost";
	private String port = "1521";
	private String dbName = "AFDB";
	private String username ="afdbAdmin";
	private String passwd = "afdbAdmin0";
	private String driver = "oracle.jdbc.driver.OracleDriver";
	private String url = "";
	
	private static HashMap<String, String> databaseInfo = new HashMap<String, String>();
	
	
	public enum DatabaseType {
		ORACLE,
		MYSQL
	}
	
	public DatabaseConnector() throws Exception {
		if (databaseInfo.size() != 6 ) {
			throw new Exception("Property File does not have enough information to connect to the database. Please check property file (cdcwebapp.properties)");
		}
		
		configureDatabase();
	}
	
	private void configureDatabase() {
		serverAddress = databaseInfo.get("DATABASE_URL");
		port = databaseInfo.get("DATABASE_PORT");
		dbName = databaseInfo.get("DATABASE_NAME");
		username = databaseInfo.get("DATABASE_USER");
		passwd = databaseInfo.get("DATABASE_PSWD");
		
		String type = databaseInfo.get("DATABASE_TYPE");
		
		if (type.toLowerCase().contains("oracle")) {
			driver = ORACLE_DRIVER;
			url = String.format("jdbc:oracle:thin:@%s:%s:%s", serverAddress, port, dbName);
		} else {
			driver = MYSQL_DRIVER;
			url = String.format("jdbc:mysql://%s:%s/%s", serverAddress, port, dbName);
		}
		
		
	}

	public DatabaseConnector(DatabaseType type) {
		switch(type) {
		case ORACLE:
			initializeOracle();
			break;
		case MYSQL:
			initializeMySQL();
			break;
		}
	}

	private void initializeMySQL() {
		port = "3306";
		dbName = "airforce_cdcs";
		driver = "com.mysql.jdbc.Driver";
		username = "root";
		passwd = "fall0ut2k";
		url = String.format("jdbc:mysql://%s:%s/%s", serverAddress, port, dbName);
	}

	private void initializeOracle() {
		port = "1521";
		dbName = "AFDB";
		username ="afdbAdmin";
		passwd = "afdbAdmin0";
		driver = "oracle.jdbc.driver.OracleDriver";
		url = String.format("jdbc:oracle:thin:@%s:%s:%s", serverAddress, port, dbName);
	}
	
	public String getURL() {
		return url;
	}
	
	public String getPort() {
		return port;
	}
	
	public String getDatabaseName() {
		return dbName;
	}
	
	public String getDriver() {
		return driver;
	}
	
	public String getUser() {
		return username;
	}
	
	public String getPassword() {
		return passwd;
	}
 	
	public static HashMap<String, String> getDatabaseInfo() {
		return databaseInfo;
	}
	

}
